package ecarx.com.cn.ecarxproject;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.ToggleButton;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import ecarx.com.cn.ecarxproject.business.bluetooth.BlueAdmin;


import static android.bluetooth.BluetoothAdapter.EXTRA_STATE;

public class MainActivity extends AppCompatActivity {


    private ListView lvBTDevices;

    private ToggleButton tbtnSwitch;

    private Button searchBotton;
    private Button exitButton;

    ArrayAdapter<String> adtDevices;
    List<String> lstDevices = new ArrayList<>();
    BluetoothAdapter btAdapt;

    private BluetoothSocket btSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tbtnSwitch = (ToggleButton) findViewById(R.id.toggleButton);
        // ListView及其数据源 适配器
        lvBTDevices = (ListView) this.findViewById(R.id.scanResult);

        searchBotton = (Button) this.findViewById(R.id.search);
        exitButton = (Button) this.findViewById(R.id.exit);

        searchBotton.setOnClickListener(new ClickEvent());
        exitButton.setOnClickListener(new ClickEvent());

        adtDevices = new ArrayAdapter<>(this,
                android.R.layout.simple_list_item_1, lstDevices);
        lvBTDevices.setAdapter(adtDevices);
        lvBTDevices.setOnItemClickListener(new ItemClickEvent());

        btAdapt = BluetoothAdapter.getDefaultAdapter();// 初始化本机蓝牙功能

        tbtnSwitch.setOnClickListener(new ClickEvent());

        if (btAdapt.isEnabled())
            tbtnSwitch.setChecked(false);
        else
            tbtnSwitch.setChecked(true);

        // 注册Receiver来获取蓝牙设备相关的结果  
        String ACTION_PAIRING_REQUEST = "android.bluetooth.device.action.PAIRING_REQUEST";
        IntentFilter intent = new IntentFilter();
        intent.addAction(BluetoothDevice.ACTION_FOUND);// 用BroadcastReceiver来取得搜索结果   
        intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intent.addAction(ACTION_PAIRING_REQUEST);
        intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
        intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(searchDevices, intent);

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    MQTTClient.main();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

//--------------------------------------------------- 

    private BroadcastReceiver searchDevices = new BroadcastReceiver() {

        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Bundle b = intent.getExtras();
            Object[] lstName = b.keySet().toArray();

            // 显示所有收到的消息及其细节   
            for (int i = 0; i < lstName.length; i++) {
                String keyName = lstName[i].toString();
                Log.e(keyName, String.valueOf(b.get(keyName)));
            }
            BluetoothDevice device = null;
            // 搜索设备时，取得设备的MAC地址   
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() == BluetoothDevice.BOND_NONE) {
                    String str = "未配对|" + device.getName() + "|"
                            + device.getAddress();
                    if (lstDevices.indexOf(str) == -1)// 防止重复添加   
                        lstDevices.add(str); // 获取设备名称和mac地址   
                    adtDevices.notifyDataSetChanged();


                    try {
                        BlueAdmin.setPin(device.getClass(), device, "0000");
                    } catch (Exception e) {
                        // TODO Auto-generated catch block 
                        e.printStackTrace();
                    }
                    try {
                        BlueAdmin.cancelPairingUserInput(device.getClass(), device);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block 
                        e.printStackTrace();
                    }

                }
            } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING:
                        Log.d("BlueToothTestActivity", "正在配对......");
                        break;
                    case BluetoothDevice.BOND_BONDED:
                        Log.d("BlueToothTestActivity", "完成配对");
                        connect(device);//连接设备   
                        break;
                    case BluetoothDevice.BOND_NONE:
                        Log.d("BlueToothTestActivity", "取消配对");
                    default:
                        break;
                }
            }else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                int state = intent.getIntExtra(EXTRA_STATE,-1);
                switch (state){
                    case BluetoothAdapter.STATE_ON:
                        tbtnSwitch.setChecked(false);
                        Toast.makeText(MainActivity.this,"蓝牙已打开",Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothAdapter.STATE_TURNING_ON:
                        Toast.makeText(MainActivity.this,"蓝牙正在打开",Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothAdapter.STATE_TURNING_OFF:
                        Toast.makeText(MainActivity.this,"蓝牙正在关闭",Toast.LENGTH_SHORT).show();
                        break;
                    case BluetoothAdapter.STATE_OFF:
                        tbtnSwitch.setChecked(true);
                        Toast.makeText(MainActivity.this,"蓝牙已关闭",Toast.LENGTH_SHORT).show();
                        break;
                }
            }


          /*  if (intent.getAction().equals("android.bluetooth.device.action.PAIRING_REQUEST")) {

                Log.e("tag111111111111111", "ddd");
                BluetoothDevice btDevice = intent
                        .getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                // byte[] pinBytes = BluetoothDevice.convertPinToBytes("1234"); 
                // device.setPin(pinBytes); 

                try {
                    BlueAdmin.setPin(btDevice.getClass(), btDevice, "0000"); // 手机和蓝牙采集器配对 
                    BlueAdmin.createBond(btDevice.getClass(), btDevice);
                    BlueAdmin.cancelPairingUserInput(btDevice.getClass(), btDevice);
                } catch (Exception e) {
                    // TODO Auto-generated catch block 
                    e.printStackTrace();
                }
            }*/
        }
    };

    class ItemClickEvent implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                long arg3) {
            if (btAdapt.isDiscovering()) btAdapt.cancelDiscovery();
            String str = lstDevices.get(arg2);
            String[] values = str.split("\\|");
            String address = values[2];
            Log.e("address", values[2]);
            BluetoothDevice btDev = btAdapt.getRemoteDevice(address);
            try {
                Boolean returnValue = false;
                if (btDev.getBondState() == BluetoothDevice.BOND_NONE) {
                    //利用反射方法调用BluetoothDevice.createBond(BluetoothDevice remoteDevice);   
//                    Method createBondMethod = BluetoothDevice.class.getMethod("createBond");
                  Log.d("BlueToothTestActivity", "开始配对");
//                    returnValue = (Boolean) createBondMethod.invoke(btDev);
                    BlueAdmin.pair(address, "0000");
                    showMessage("here");
                } else if (btDev.getBondState() == BluetoothDevice.BOND_BONDED) {
                    connect(btDev);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void connect(BluetoothDevice btDev) {
        final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
        UUID uuid = SPP_UUID;
        try {
            btSocket = btDev.createRfcommSocketToServiceRecord(uuid);
            Log.d("BlueToothTestActivity", "开始连接...");
            btSocket.connect();
        } catch (IOException e) {
            // TODO Auto-generated catch block   
            e.printStackTrace();
        }
    }

    class ClickEvent implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            if (v == searchBotton)// 搜索蓝牙设备，在BroadcastReceiver显示结果
            {
                if (btAdapt.getState() == BluetoothAdapter.STATE_OFF) {// 如果蓝牙还没开启   
                    Toast.makeText(MainActivity.this, "请先打开蓝牙", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (btAdapt.isDiscovering()) {
                    btAdapt.cancelDiscovery();
                }
                lstDevices.clear();
                Object[] lstDevice = btAdapt.getBondedDevices().toArray();
                for (int i = 0; i < lstDevice.length; i++) {
                    BluetoothDevice device = (BluetoothDevice) lstDevice[i];
                    String str = "已配对|" + device.getName() + "|"
                            + device.getAddress();
                    lstDevices.add(str); // 获取设备名称和mac地址   
                    adtDevices.notifyDataSetChanged();
                }
                setTitle("本机蓝牙地址：" + btAdapt.getAddress());
                btAdapt.startDiscovery();
            } else if (v == tbtnSwitch) {// 本机蓝牙启动/关闭   
                if (tbtnSwitch.isChecked() == false){
                    btAdapt.enable();
                }else {
                    btAdapt.disable();
                }
            } else if (v == exitButton) {
                try {
                    if (btSocket != null)
                        btSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                MainActivity.this.finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        this.unregisterReceiver(searchDevices);
        super.onDestroy();
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public void showMessage(String str) {
        Toast.makeText(this, str, Toast.LENGTH_LONG).show();
    }
}
